import re
import time
import random
from utils.file_operation import (
    load_json_to_dict,
    extract_quantity_and_unit,
    save_dict_to_json,
    generate_groups,
)
from utils.convert import convert_rem_to_px
from rj.rjmart.pre_api_cx import pre_api_get

# from rj.rjmart.pre_api_ls import pre_api_get
import pandas as pd
from website.greniner.index import process_data

# from website.procell.index import process_data

rj = pre_api_get()
# data = load_json_to_dict("total_list.json")
# data_list = []


def remove_html_tags(text):
    # 使用正则表达式移除所有HTML标签
    clean_text = re.sub(r"<[^>]+>", "", text)
    return clean_text


def gen_upload_dict(rj_item: dict):
    """
    单规格生成 rj 商品上传 dict

    Args:
        rj_item (dict): rj 商品信息
        brand_id (int): 品牌 id

    Returns:
        dict: 商品上传 dict
    """

    # _unit = rj_item["packageSpecification"].split("/")[-1]

    # _desc = BeautifulSoup(rj_item["desc"], "html.parser").find(
    #     "div", class_="detail-product-info-intro"
    # )

    _sku_list = []

    for sku in rj_item["specifications"]:
        _sku_list.append(
            {
                "code": sku["goodCode"],
                "price": sku["price"],
                "directoryPrice": round(sku["price"] * 1.9),
                "stock": 999,
                "carryFeeTemplateId": 4611,
                "skuAttributes": [
                    # 生物试剂填写
                    {
                        "attributeName": "产品规格",
                        "attributeValue": sku["attrNameToValueMap"].get("产品规格", ""),
                    },
                ],
                "deliveryTime": (sku["deliveryTime"] if sku["deliveryTime"] else -1),
            }
        )

    return {
        # "code": rj_item["spuCode"],
        "code": rj_item["code"],
        # "name": (rj_item["name"]).split("纽英伦(NEB) ")[-1],
        # "name": remove_html_tags(rj_item["name"]),
        "name": rj_item["name"],
        # 商品品牌 id
        # "brandId": 1784,
        "brandId": 251,
        "categoryId": rj_item["categoryId"],
        "dangerousInfo": {"casNo": rj_item["casNo"] if rj_item["casNo"] else ""},
        # 从列表获取图片
        # "photos": [{"photo": url} for url in rj_item["detailPhotos"][0]],
        # "photos": [{"photo": rj_item["detailPhotos"][0]} for _ in range(5)],
        # "photos": [{"photo": rj_item["detailPhotos"][0]} for _ in range(5)],
        # "photos": [
        #     {"photo": rj_item["detailPhotos"][0]},
        #     {
        #         "photo": "https://bio-mercury-1316961827.cos.ap-guangzhou.myqcloud.com/photos/invivogen/logo_invivogen.png"
        #     },
        #     {
        #         "photo": "https://bio-mercury-1316961827.cos.ap-guangzhou.myqcloud.com/photos/invivogen/logo_invivogen.png"
        #     },
        #     {
        #         "photo": "https://bio-mercury-1316961827.cos.ap-guangzhou.myqcloud.com/photos/invivogen/logo_invivogen.png"
        #     },
        #     {
        #         "photo": "https://bio-mercury-1316961827.cos.ap-guangzhou.myqcloud.com/photos/invivogen/logo_invivogen.png"
        #     },
        # ],
        # 自定义图片
        "photos": [{"photo": rj_item["photo"]} for _ in range(5)],
        # "unit": "支",
        "unit": rj_item["unit"],
        # 单次填写
        "desc": rj_item["description"],
        # "desc": str(_desc),
        "status": 3,
        # "skuInfos": [
        #     {
        #         # "code": "S1067-10mg",
        #         "code": rj_item["spuCode"],
        #         "price": rj_item["price"],
        #         "directoryPrice": round(rj_item["price"] * 1.9),
        #         "stock": 999,
        #         "carryFeeTemplateId": 4611,
        #         # 生物试剂，实验耗材该项不填
        #         # 化学试剂填写
        #         # "specification": {
        #         #     "packingSpecificationValue": 0,
        #         #     "packingSpecificationUnit": "",
        #         #     "minSpecificationValue": 0,
        #         #     "minSpecificationUnit": "",
        #         # },
        #         "skuAttributes": [
        #             # 生物试剂填写
        #             {
        #                 "attributeName": "产品规格",
        #                 "attributeValue": rj_item["specification"],
        #             },
        #             # 实验耗材填写
        #             {
        #                 "attributeName": "包装规格",
        #                 "attributeValue": rj_item["specification"],
        #             },
        #         ],
        #         "deliveryTime": (
        #             rj_item["deliveryTime"] if rj_item["deliveryTime"] else -1
        #         ),
        #     }
        # ],
        "skuInfos": _sku_list,
    }


# import os


# def get_file_list(folder_path):
#     try:
#         # 获取指定路径下所有文件和文件夹
#         items = os.listdir(folder_path)
#         # 仅返回文件（可以根据需要过滤文件夹）
#         files = [
#             item for item in items if os.path.isfile(os.path.join(folder_path, item))
#         ]
#         file_names = [item.split(".")[0] for item in files]
#         return file_names
#     except Exception as e:
#         return str(e)

# data_list = load_json_to_dict("upload_list.json")
# for group in generate_groups(data_list):
#     res = rj.batchSaveOrUpdateProductV2(group)
#     print(res.json())
#     time.sleep(1)


def gen_multi_specification_dict(sku_code: str, data_list: list):
    res_dict = {
        "code": sku_code,
        "name": remove_html_tags(data_list[0]["name"]),
        # 品牌 id
        "brandId": 1865,
        "categoryId": data_list[0]["categoryId"],
        "dangerousInfo": {
            "casNo": data_list[0]["casNo"] if data_list[0]["casNo"] else ""
        },
        # "photos": [{"photo": url} for url in rj_item["detailPhotos"]],
        "photos": [
            {
                "photo": "https://images.rjmart.cn/image/d15682ec/cacdel/27f1099c-47f5-4161-bb70-a24bb270ea40.jpeg"
            },
        ],
        "unit": "支",
        # 单次填写
        "desc": "测试商品内容",
        "status": 3,
        "skuInfos": [],
    }
    for item in data_list:
        res_dict["skuInfos"].append(
            {
                "code": item["spuCode"],
                "price": item["price"],
                "directoryPrice": round(item["price"] * 1.9),
                "stock": 999,
                "carryFeeTemplateId": 4611,
                # 生物试剂，实验耗材该项不填
                # 化学试剂填写
                # "specification": {
                #     "packingSpecificationValue": 0,
                #     "packingSpecificationUnit": "",
                #     "minSpecificationValue": 0,
                #     "minSpecificationUnit": "",
                # },
                "skuAttributes": [
                    # 生物试剂填写
                    {
                        "attributeName": "产品规格",
                        "attributeValue": item["specification"],
                    }
                    # 实验耗材填写
                    # {
                    #     "attributeName": "包装规格",
                    #     "attributeValue": item["specification"],
                    # }
                ],
                "deliveryTime": (item["deliveryTime"] if item["deliveryTime"] else -1),
            }
        )
    return res_dict


def gen_rj_multi_spec_dict(pro_dict: dict) -> dict:
    """rj多规格生成

    适合rj店铺前端页面已显示多规格信息商品
    """

    #  判断是否存在多规格
    if len(pro_dict["specifications"]) > 1:
        _temp_list = pro_dict["code"].split("-")
        _code = "-".join(_temp_list[:-1])
    else:
        _code = pro_dict["code"]

    res_dict = {
        "code": _code,
        "name": pro_dict["name"],
        # 品牌 id
        "brandId": pro_dict["brandId"],
        "categoryId": pro_dict["categoryId"],
        "dangerousInfo": {"casNo": pro_dict["casNo"] if pro_dict["casNo"] else ""},
        # "photos": [{"photo": url} for url in pro_dict["detailPhotos"]],
        # "photos": [{"photo": pro_dict["photo"]} for _ in range(5)],
        "photos": [{"photo": "https://bio-mercury-1316961827.cos.ap-guangzhou.myqcloud.com/photos/Synaptic_Systems/main.png"} for _ in range(5)],
        "unit": pro_dict["unit"],
        # 单次填写
        "desc": convert_rem_to_px(pro_dict["description"]),
        "status": 3,
        "skuInfos": [],
    }
    for item in pro_dict["specifications"]:
        _spec = item["specification"].split(":")[-1]
        res_dict["skuInfos"].append(
            {
                "code": item["goodCode"],
                "price": item["price"],
                "directoryPrice": round(item["price"] * 1.9),
                "stock": 999,
                # 辰星
                "carryFeeTemplateId": 4611,
                # 莱思
                # "carryFeeTemplateId": 7114,
                # 生物试剂，实验耗材该项不填
                # 化学试剂填写
                # "specification": {
                #     "packingSpecificationValue": 0,
                #     "packingSpecificationUnit": "",
                #     "minSpecificationValue": 0,
                #     "minSpecificationUnit": "",
                # },
                "skuAttributes": [
                    # 生物试剂填写
                    {
                        "attributeName": "产品规格",
                        # "attributeValue": item["attrNameToValueMap"]["产品规格"],
                        "attributeValue": _spec,
                    }
                    # 实验耗材填写
                    # {
                    #     "attributeName": "包装规格",
                    #     "attributeValue": _spec,
                    # }
                ],
                "deliveryTime": (item["deliveryTime"] if item["deliveryTime"] else -1),
            }
        )
    return res_dict


if __name__ == "__main__":

    # 🎉生成商品数据列表
    # upload_list = []
    # data_list = load_json_to_dict("total_list.json")
    # for item in data_list:
    #     print(item["spuCode"])
    #     try:
    #         upload_dict = gen_upload_dict(item)
    #         _desc, _image = process_data(item["spuCode"])
    #         if _desc:
    #             upload_dict["desc"] = convert_rem_to_px(_desc)
    #             upload_dict["photos"] = [{"photo": _image} for _ in range(5)]
    #             res = rj.batchSaveOrUpdateProductV2([upload_dict])
    #             print(res.json())
    #         # 随机等待10到20秒
    #         time.sleep(random.randint(10, 20))
    #     except Exception as e:
    #         print(e)
    #         continue

    # 🎉上传商品列表
    # data_list = load_json_to_dict("upload_list.json")
    # for group in generate_groups(data_list):
    #     res = rj.batchSaveOrUpdateProductV2(group)
    #     print(res.json())
    #     time.sleep(1)

    # 🎉直接生成上传商品列表
    # data_list = load_json_to_dict("total_list.json")
    # res_list = []
    # for item in data_list:
    #     _procode = item["spuCode"]
    #     item = gen_upload_dict(item)
    #     res_list.append(item)
    #     # res = rj.batchSaveOrUpdateProductV2([item])
    #     # print(res.json())
    #     # break
    # for group in generate_groups(res_list):
    #     res = rj.batchSaveOrUpdateProductV2(group)
    #     print(res.json())
    #     time.sleep(1)

    # 单个上传测试

    upload_list = []
    data_list = load_json_to_dict("total_list_with_desc.json")
    for item in data_list:
        temp_dict = gen_rj_multi_spec_dict(item)
        upload_list.append(temp_dict)
        # print(temp_dict)
        # break
    #     print(item["spuCode"])
    #     upload_dict = gen_upload_dict(item)
    #     _desc = process_data(item["spuCode"])
    #     if _desc:
    #         upload_dict["desc"] = convert_rem_to_px(_desc)
    #         # item["desc"] = _desc
    #         upload_list.append(upload_dict)
    #     time.sleep(3)

    for group in generate_groups(upload_list):
        res = rj.batchSaveOrUpdateProductV2(group)
        print(res.json())
        time.sleep(1)
